<template>
  <a-drawer v-if="visible" :append-to-body="true" :width="540" :visible="visible" :closable="false" @cancel="close()"
    @ok="saveNode()" ok-text="保存">
    <template #title>
      <EditableText :value="flowNodeConfig.name" @change="onNodeNameChange" />

    </template>

    <div class="approver-drawer__content">

      <!-- 节点审批类型 -->
      <!-- <div class="approval-editor-node-type-wrapper">
          <div class="item-key-wrapper">
            <div class="item-key">审批类型</div>
          </div>
          <div class="item-content">
            <a-radio-group v-model="flowNodeConfig.approvalType">
              <a-radio :value="0">人工审批</a-radio>
              <a-radio :value="1">自动通过</a-radio>
              <a-radio :value="2">自动拒绝</a-radio>
            </a-radio-group>
          </div>
        </div> -->

      <!-- 审批人选择界面 -->
      <div class="approval-editor-tab-wrapper">
        <a-radio-group type="button" v-model="viewEditorType" size="large">
          <a-radio :value="0">设置审批人</a-radio>
          <a-radio :value="1">操作权限</a-radio>
        </a-radio-group>

        <!-- 设置审批人 -->
        <div class="item-content-editor" v-if="viewEditorType == 0">
          <div class="content-wrap">
            <div class="item-content">
              <!-- 审批人列表 -->
              <div class="item-wrap approver">
                <div class="approver-list">
                  <div class="approver-wrapper" v-for="(item, idx) in flowNodeConfig.assignees">
                    <div class="header">
                      <span>审批人{{ idx + 1 }}</span>
                      <icon-delete :style="{ fontSize: '18px' }" @click="delApprover(item)"
                        v-if="flowNodeConfig.assignees.length > 1" />
                    </div>
                    <div class="main-content">
                      <a-radio-group class="radio-group" v-model="item.assignType"
                        @change="onAssigneeTypeChanged(item)">
                        <a-grid :cols="3" :colGap="0" :rowGap="10">
                          <a-grid-item><a-radio :value="'SELF'">发起人本人</a-radio></a-grid-item>
                          <a-grid-item><a-radio :value="'DEPT'">部门</a-radio></a-grid-item>
                          <a-grid-item><a-radio :value="'ROLE'">角色</a-radio></a-grid-item>
                          <a-grid-item><a-radio :value="'USER'">指定成员</a-radio></a-grid-item>
                        </a-grid>
                      </a-radio-group>
                    </div>
                    <div class="sub-content">
                      <div class="sub-content-top-line"></div>
                      <template v-if="item.assignType == 'DEPT'">
                        <p class="bold">选择部门</p>
                        <a-form-item tooltip="请选择部门" label="部门名称">
                          <a-select :allow-search="{ retainInputValue: true }" placeholder="请选择部门"
                            v-model="item.assignId">
                            <a-option v-for="dept in organStore.depts" :value="dept.id" :label="dept.name"></a-option>
                          </a-select>
                        </a-form-item>
                      </template>
                      <template v-else-if="item.assignType == 'ROLE'">
                        <p class="bold">选择角色</p>
                        <a-form-item tooltip="请选择角色" label="组织角色">
                          <a-select :allow-search="{ retainInputValue: true }" placeholder="请选择角色"
                            v-model="item.assignId">
                            <a-option v-for="role in organStore.roles" :value="role.id" :label="role.name"></a-option>
                          </a-select>
                        </a-form-item>
                      </template>
                      <template v-else-if="item.assignType == 'USER'">
                        <p class="bold">添加成员<span></span></p>
                        <div class="assignee-box">
                          <a-button size="small" @click="onAssigneeClick(item)"><icon-plus /></a-button>
                          <span class="assignee-list">
                            <a-tag v-for="userId in item.assignees">{{ getUserById(userId).name }}</a-tag>
                          </span>
                          <OrganChooseBox v-if="showChooseAssignee" v-model:visible="showChooseAssignee"
                            v-model:selected="selectedAssignee.assignees" :hidden-dept="true" :hidden-role="true" />
                        </div>
                      </template>
                    </div>
                  </div>
                </div>

                <!-- 添加审核人按钮 -->
                <div class="add-operator">
                  <a-link @click="addApprover()" v-if="!onlyOneNode">
                    <template #icon><icon-plus /></template>添加审批人
                  </a-link>
                </div>
                <div class="item-wrap sign-type">
                  <div class="item-key-wrapper">
                    <div class="item-key">可决策节点</div>
                  </div>
                  <div class="item-content">
                    <a-form-item tooltip="请选择节点" label="选择节点">
                      <a-select multiple :allow-search="{ retainInputValue: true }" placeholder="请选择节点"
                        v-model="flowNodeConfig.nodeIds">
                        <a-option v-for="node in nodeOptions" :value="node.id" :label="node.name"></a-option>
                      </a-select>
                    </a-form-item>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 设置操作权限 -->
        <div class="item-content-auth" v-else-if="viewEditorType == 1">
          <div class="content-wrap">
            <div class="item-content">
              <div class="item-wrap auth-list">
                <a-checkbox class="auth-item" v-model="flowNodeConfig.enableProxy" :value="1">允许代理</a-checkbox>
                <a-checkbox class="auth-item" v-model="flowNodeConfig.enableAdd" :value="1">允许加签</a-checkbox>
                <a-checkbox class="auth-item" v-model="flowNodeConfig.enableBack" :value="1">允许回退</a-checkbox>
              </div>
              <div class="item-wrap tip">
                <div class="item-key-wrapper">
                  <p class="item-key">提示：</p>
                </div>
                <div class="more-info">
                  <p>加签为临时增加审核流程节点</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-drawer>
</template>

<script setup>
import useApp from "@/hooks";
const { $ } = useApp();
import ArrayUtil from "../common/ArrayUtil";
import Snowflake from "../common/Snowflake";
import { NODE } from "../common/FlowConstant";
import OrganChooseBox from "../dialog/OrganChooseBox.vue";
import { IconDelete, IconSwap, IconPlus } from "@arco-design/web-vue/es/icon";
import EditableText from "@/components/common/EditableText.vue";
import useOrgStore from "@/stores/modules/organ";
const organStore = useOrgStore();
import FlowDefine from "@/api/FlowDefine";
const nodeOptions = ref([])
import { useFlowStore } from "@/stores/index";
const flow = useFlowStore();
const visible = ref(false);
$.on(NODE.DECISION + '-drawer-open', config => {
  flowNodeConfig.value = config;
  visible.value = true;
  buildOptions()
})
let viewEditorType = ref(0); // 界面编辑类型    0:审批人; 1:表单权限; 2:操作权限
let flowNodeConfig = ref({
  // type: 1,
  // approvalType: 0,
  // multiInstanceApprovalType: 0,
  // flowNodeNoAuditorType: 0,
  // flowNodeSelfAuditorType: 0,
  // assignees: [
  // {
  //   id: Snowflake.generate(),
  //   assigneeType: 0,
  //   layerType: 0,
  // },
  // ],
});
function buildOptions() {
  FlowDefine.parserOne({
    flowDefine: JSON.stringify(flow.nodeConfig),
    flowDefineType: 'EDA'
  }).then(res => {
    let arr = res;
    arr = arr.filter(ele => {
      return ele.nodeType != NODE.START
    })
    nodeOptions.value = arr;
  })
}
// 是否为单个审批人节点
let onlyOneNode = computed(() => {
  let fristAssigneeType = flowNodeConfig.value.assignees[0].assigneeType;
  return [5, 6, 7].includes(fristAssigneeType);
});
// 审批人选择指定成员
let showChooseAssignee = ref(false); // 是否显示指定成员对话框
let selectedAssignee = ref({}); // 当前选中的单个审批人设置
const onAssigneeClick = (item) => {
  selectedAssignee.value = item;
  showChooseAssignee.value = true;
};


watch(
  flowNodeConfig,
  (newVal) => {
    if (newVal.assignees.length == 1) {
      // 只设置了一个审批人
      let fristAssigneeType = flowNodeConfig.value.assignees[0].assigneeType;
      // 是否设置连续多级上级,连续多级部门负责人
      if ([5, 6].includes(fristAssigneeType)) {
        flowNodeConfig.value.multiInstanceApprovalType = 3;
      }

      // 是否设置了发起人自选，角色，指定审批人
      if ([3, 4, 7].includes(fristAssigneeType) && [0, 3].includes(flowNodeConfig.value.multiInstanceApprovalType)) {
        if (flowNodeConfig.value.multiInstanceApprovalType == 0) {
          flowNodeConfig.value.multiInstanceApprovalType = 1;
        }
      }
    } else {
      // 如果设置了多个审批人，默认会签
      if (flowNodeConfig.value.multiInstanceApprovalType == 0) {
        flowNodeConfig.value.multiInstanceApprovalType = 1;
      }
    }
  },
  { deep: true }
);



// 审批人类型切换时
const onAssigneeTypeChanged = (assignee) => {
  console.log("审批人类型切换时", assignee);
  let { assigneeType } = assignee;
  if ([1, 2, 5, 6].includes(assigneeType)) {
    assignee.layerType = 0;
    assignee.layer = 0;
    delete assignee.roles;
    delete assignee.assignees;
  } else if ([0, 7].includes(assigneeType)) {
    delete assignee.layerType;
    delete assignee.layer;
    delete assignee.roles;
    delete assignee.assignees;
  } else if ([3].includes(assigneeType)) {
    delete assignee.layerType;
    delete assignee.layer;
    delete assignee.assignees;
  } else if ([4].includes(assigneeType)) {
    assignee.assignees = [];
    delete assignee.layerType;
    delete assignee.layer;
    delete assignee.roles;
  }
};

// 添加审批人
const addApprover = () => {
  flowNodeConfig.value.assignees.push({
    rid: Snowflake.generate(),
    assigneeType: 0,
  });
};

// 删除审批人
const delApprover = (approver) => {
  ArrayUtil.remove(flowNodeConfig.value.assignees, "rid", approver.rid);
  // 当设置的审批人删除到一个时。节点类型设置为：非多实例审批
  if (flowNodeConfig.value.assignees.length === 1) {
    flowNodeConfig.value.multiInstanceApprovalType = 0;
  }
};

// 编辑节点名称
const onNodeNameChange = (name) => {
  flowNodeConfig.value.name = name;
  saveNode(false);
};

const saveNode = (leave = true) => {
  // setApproverConfig({
  //   value: toRaw(flowNodeConfig.value),
  //   flag: true,
  //   id: _uid,
  // });
  close();
};

const close = () => {
  visible.value = false;
};

onBeforeMount(() => { });
onMounted(() => { });
</script>

<style lang="less">
@import "./style/common.less";

.approver-drawer__content {
  user-select: none;

  .approval-editor-tab-wrapper {
    // margin-top: 24px;

    .item-content-editor,
    .item-content-auth {
      margin-top: 8px;

      .approver-list {
        .approver-wrapper {
          border: 1px solid #e4e5e7;
          border-radius: 6px;
          overflow: hidden;

          +.approver-wrapper {
            margin-top: 6px;
          }

          .header {
            padding: 0 16px;
            background: #f5f6f7;
            height: 36px;
            line-height: 36px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            span {
              color: #1f2329;
              font-weight: 600;
            }

            .arco-icon {
              cursor: pointer;

              &:hover {
                color: #3370ff;
              }
            }
          }

          // .main-content {
          // }

          .sub-content {
            padding: 0 16px 10px;

            .sub-content-top-line {
              border-top: 1px solid #dee0e3;
            }

            p {
              padding-top: 10px;
              color: #1f2329;
              font-size: 14px;
              font-weight: 600;
              margin-bottom: 8px;

              span {
                color: #8f959e;
                font-weight: 400;
                font-size: 13px;
              }
            }

            .arco-form-item {
              margin-bottom: 0;
            }

            .assignee-box {
              display: flex;
              align-items: center;
              justify-content: space-between;

              .assignee-list {
                flex: 1;
                margin-left: 10px;
                display: flex;
                flex-wrap: wrap;
                gap: 4px;

                .arco-tag {
                  height: 28px;
                }
              }
            }
          }

          .radio-group {
            padding: 10px 16px;
            width: 100%;

            .arco-radio {
              margin-right: 2px;
            }
          }
        }
      }

      .add-operator {
        margin-top: 8px;
      }

      .item-wrap {
        +.item-wrap {
          margin-top: 24px;
        }
      }

      .approver-null-select-box {
        margin-top: 8px;
      }

      .auth-list {
        display: flex;
        flex-direction: column;

        .auth-item {
          margin-top: 10px;
        }
      }

      .more-info {
        line-height: 20px;
        color: #646a73;

        p {
          position: relative;
          padding-left: 10px;
          margin-top: 8px;

          &::before {
            content: "";
            width: 4px;
            height: 4px;
            position: absolute;
            top: 9px;
            left: 0;
            border-radius: 2px;
            background: #3370ff;
          }
        }
      }
    }
  }

  .arco-radio-group-button {
    width: 100%;

    .arco-radio-button {
      flex: 1;
      text-align: center;
    }
  }

  .item-key-wrapper {
    .item-key {
      color: #1f2329;
      font-weight: 600;
    }
  }

  .item-content {
    margin-top: 8px;
  }
}

.switch-container {
  user-select: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  margin: 0 12px;

  .select-tip {
    color: #646a73;
  }
}
</style>